package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.FoodDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Food;
import com.itheima.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service(interfaceClass = FoodService.class)
@Transactional
public class FoodServiceImpl implements FoodService {

    @Autowired
    private FoodDao foodDao;

    @Override
    public void add(List<Food> foodList) {
        //判断是否为空
        if(foodList!=null&&foodList.size()>0){
            for (Food food : foodList) {
                //查询此膳食名称是否存在
                Long count= foodDao.findCountByFoodName(food.getFoodName());
                if(count>0){
                    //存在则修改
                    foodDao.editByFoodName(food);
                }else {
                    //不存在则添加
                    foodDao.add(food);
                }
            }
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用PageHelper进行分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<Food> page = foodDao.selectByCondition(queryString);

        //将Page对象转换为PageResult对象
        PageResult result = new PageResult(page.getTotal(),page.getResult());

        return result;
    }

    @Override
    public List<Food> finAll() {
        return foodDao.findAll();
    }

    @Override
    public List<String> findFoodByOrderDate(Date date) {
        int id = foodDao.findInterventionIdByOrderDate(date);
        return foodDao.findFoodNameByInterventionId(id);
    }

    @Override
    public void addFood(Food food) {
        foodDao.addFood(food);
    }

    @Override
    public void edit(Food food) {
        foodDao.edit(food);
    }

    @Override
    public Food findById(Integer foodId) {
        return foodDao.findById(foodId);
    }

    @Override
    public void deleteById(Integer id) {
        foodDao.deleteById(id);
    }
}
